﻿/* ==============================================================================
*
*   Copyright (c) 2010, Pierre Favier
*   All rights reserved.
*
*   NTasking is free software: you can redistribute it and/or modify it
*   under the terms of the GNU General Public License as published by the
*   Free Software Foundation.
*
*   Redistribution and use in source and binary forms, with or without
*   modification, are permitted provided that the following conditions
*   are met:
*
*   -   Redistributions of source code must retain the above copyright notice,
*       this list of conditions and the following disclaimer.
*
*   -   Redistributions in binary form must reproduce the above
*       copyright notice, this list of conditions and the following
*       disclaimer in the documentation and/or other materials
*       provided with the distribution.
*
*   THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
*   WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
*   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
*   BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
*   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
*   TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
*   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
*   ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
*   TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
*   THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
*   SUCH DAMAGE.
*
* ============================================================================== */

using System;
using NTasking.Internals;
using Void = NTasking.Internals.Void;

namespace NTasking
{

    public static class SelectEx
    {

        #region Internal Classes
        
        public class AsynchronousSelect
        {
            
            internal readonly MethodCall Call;


            internal AsynchronousSelect(MethodCall call)
            {
                Call = call;
            }
            
            
            public void ThenAbort(Action abortablePart)
            {
                if (abortablePart == null)
                    throw Errors.AbortablePartIsNull();
                    
                SynchronizedObject.AsynchronousSelect(Call, abortablePart);
                
                if (Call.Context.ResultIsSet)
                    Call.Continue();
            }
            
        }
        
        
        public class SelectiveCall : AsynchronousSelect
        {
            
            internal SelectiveCall(MethodCall call)
                : base(call)
            {
            }
            
            
            public void Else(Action elseAlternative)
            {
                if (elseAlternative == null)
                    throw Errors.ElseAlternativeIsNull();
                    
                SynchronizedObject.ConditionalEntryCall(Call);
                
                if (Call.Context.ResultIsSet)
                    Call.Continue();
            }
            
            
            public void OrDelay(DateTime until, Action delayAlternative = null)
            {
                SynchronizedObject.TimedEntryCall(Call, until);
                
                if (Call.Context.ResultIsSet)
                    Call.Continue();
                else if (delayAlternative != null)
                    delayAlternative();
            }


            public void OrDelay(int milliseconds, Action delayAlternative = null)
            {
                OrDelay(DateTime.Now.AddMilliseconds(milliseconds), delayAlternative);
            }


            public void OrDelay(Double seconds, Action delayAlternative = null)
            {
                OrDelay(DateTime.Now.AddSeconds(seconds), delayAlternative);
            }


            public void OrDelay(TimeSpan timeSpan, Action delayAlternative = null)
            {
                OrDelay(DateTime.Now + timeSpan, delayAlternative);
            }


            internal AsynchronousSelect AsAsynchronousSelect()
            {
                return new AsynchronousSelect(Call);
            }
            
        }
        
        #endregion
        
        
        #region Methods
        
        private static CallableT Callable<CallableT>(Delegate entry)
            where CallableT : class
        {
            if (entry == null)
                throw Errors.SelectiveCallIsNull();

            var callable = entry.Target as CallableT;

            if (callable == null)
                throw Errors.SelectiveCallNotSynchronized(entry);

            var method = callable as SynchronizedMethod;

            // ReSharper disable PossibleNullReferenceException
            if (!method.IsEntry)
                // ReSharper restore PossibleNullReferenceException
                throw Errors.SelectiveCallNotAnEntry(entry);

            return callable;
        }


        private static SelectiveCall CreateSelect(MethodCall call, Action continuation)
        {
            // Check that this instance can be blocked since select is an Ada
            // 'potentially blocking operation'
            if (!ThreadWrapper.CurrentThread.CanBlock)
                throw Errors.PotentiallyBlockingOperationNotAllowed("select");

            ((IContinuable)call).Continuation = continuation;
            return new SelectiveCall(call);
        }


        private static SelectiveCall CreateSelect<RetT>(MethodCall call, Action<RetT> continuation)
        {
            // Check that this instance can be blocked since select is an Ada
            // 'potentially blocking operation'
            if (!ThreadWrapper.CurrentThread.CanBlock)
                throw Errors.PotentiallyBlockingOperationNotAllowed("select");

            ((IContinuable<RetT>)call).ContextualContinuation = continuation;
            return new SelectiveCall(call);
        }

        #endregion
        

        #region EXTENSION POINTS

        #region For Methods with 0 Parameters

        public static SelectiveCall Select<RetT>(this Func<RetT> entry, Action<RetT> callStatements = null)
        {
            var call = Callable<ICallable<Func<MethodCall<RetT>>>>(entry).Intercept();

            return CreateSelect(call, callStatements);
        }


        public static SelectiveCall Select(this Action entry, Action callStatements = null)
        {
            var call = Callable<ICallable<Func<MethodCall<Void>>>>(entry).Intercept();

            return CreateSelect(call, callStatements);
        }

        #endregion


        #region For Methods with 1 Parameters

        public static SelectiveCall Select<P1T, RetT>(this Func<P1T, RetT> entry, P1T p1, Action<RetT> callStatements = null)
        {
            var call = Callable<ICallable<Func<P1T, MethodCall<RetT>>>>(entry).Intercept(p1);

            return CreateSelect(call, callStatements);
        }


        public static SelectiveCall Select<P1T>(this Action<P1T> entry, P1T p1, Action callStatements = null)
        {
            var call = Callable<ICallable<Func<P1T, MethodCall<Void>>>>(entry).Intercept(p1);

            return CreateSelect(call, callStatements);
        }

        #endregion


        #region For Methods with 2 Parameters

        public static SelectiveCall Select<P1T, P2T, RetT>(this Func<P1T, P2T, RetT> entry, P1T p1, P2T p2, Action<RetT> callStatements = null)
        {
            var call = Callable<ICallable<Func<P1T, P2T, MethodCall<RetT>>>>(entry).Intercept(p1, p2);

            return CreateSelect(call, callStatements);
        }


        public static SelectiveCall Select<P1T, P2T>(this Action<P1T, P2T> entry, P1T p1, P2T p2, Action callStatements = null)
        {
            var call = Callable<ICallable<Func<P1T, P2T, MethodCall<Void>>>>(entry).Intercept(p1, p2);

            return CreateSelect(call, callStatements);
        }

        #endregion


        #region For Methods with 3 Parameters

        public static SelectiveCall Select<P1T, P2T, P3T, RetT>(this Func<P1T, P2T, P3T, RetT> entry, P1T p1, P2T p2, P3T p3, Action<RetT> callStatements = null)
        {
            var call = Callable<ICallable<Func<P1T, P2T, P3T, MethodCall<RetT>>>>(entry).Intercept(p1, p2, p3);

            return CreateSelect(call, callStatements);
        }


        public static SelectiveCall Select<P1T, P2T, P3T>(this Action<P1T, P2T, P3T> entry, P1T p1, P2T p2, P3T p3, Action callStatements = null)
        {
            var call = Callable<ICallable<Func<P1T, P2T, P3T, MethodCall<Void>>>>(entry).Intercept(p1, p2, p3);

            return CreateSelect(call, callStatements);
        }

        #endregion


        #region For Methods with 4 Parameters

        public static SelectiveCall Select<P1T, P2T, P3T, P4T, RetT>(this Func<P1T, P2T, P3T, P4T, RetT> entry, P1T p1, P2T p2, P3T p3, P4T p4, Action<RetT> callStatements = null)
        {
            var call = Callable<ICallable<Func<P1T, P2T, P3T, P4T, MethodCall<RetT>>>>(entry).Intercept(p1, p2, p3, p4);

            return CreateSelect(call, callStatements);
        }


        public static SelectiveCall Select<P1T, P2T, P3T, P4T>(this Action<P1T, P2T, P3T, P4T> entry, P1T p1, P2T p2, P3T p3, P4T p4, Action callStatements = null)
        {
            var call = Callable<ICallable<Func<P1T, P2T, P3T, P4T, MethodCall<Void>>>>(entry).Intercept(p1, p2, p3, p4);

            return CreateSelect(call, callStatements);
        }

        #endregion

        #endregion
    }

}
